﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using Coogle.Core;

namespace Coogle.DataAccess
{
    public class SelectShippings : IFindQuery<IEnumerable<Shipping>>
    {
        private const String QUERY = @"SELECT s.Type, s.Seal, s.Weight, s.ToPort, s.FromPort, s.Ship, s.Forwarder, s.BoardingDate, s.LandingDate FROM Shippings AS s INNER JOIN Containers AS c ON s.ContainerId = c.ContainerId WHERE c.Sign=@Sign AND c.Number=@Number AND c.Checkdigit=@Checkdigit";

        private readonly ContainerCode m_containerCode;

        public SelectShippings(ContainerCode containerCode)
        {
            this.m_containerCode = containerCode;
        }

        public SqlCommand CreateCommand(SqlConnection connection)
        {
            var cmd = new SqlCommand(QUERY, connection);
            cmd.Parameters.AddWithValue("Sign", m_containerCode.Sign);
            cmd.Parameters.AddWithValue("Number", m_containerCode.Number);
            cmd.Parameters.AddWithValue("Checkdigit", m_containerCode.Check);
            return cmd;
        }

        public IEnumerable<Shipping> Map(DataTable table)
        {
            if (table == null)
                yield break;

            foreach (DataRow row in table.Rows)
                yield return Map(row);
        }

        private Shipping Map(DataRow row)
        {
            return new Shipping(row["Type"].ToString(),
                                Int32.Parse(row["Seal"].ToString()),
                                Int32.Parse(row["Weight"].ToString()),
                                row["FromPort"].ToString(),
                                row["ToPort"].ToString(),
                                row["Ship"].ToString(),
                                (Convert.IsDBNull(row["BoardingDate"])) ? null : (DateTime?)Convert.ToDateTime(row["BoardingDate"]),
                                (Convert.IsDBNull(row["LandingDate"])) ? null : (DateTime?)Convert.ToDateTime(row["LandingDate"]),
                                row["Forwarder"].ToString());
        }
    }
}
